package com.itheima.redbaby.activity;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.itheima.redbaby.BaseActivity;
import com.itheima.redbaby.GloableParams;
import com.itheima.redbaby.R;
import com.itheima.redbaby.bean.Product;
import com.itheima.redbaby.bean.ProductProperty;
import com.itheima.redbaby.engine.ProductEngine;
import com.itheima.redbaby.factory.DaoAndEngineFactory;
import com.itheima.redbaby.utils.PromptManager;
import com.itheima.redbaby.utils.SoftMap;

public class ProductDetailActivity extends BaseActivity implements OnClickListener{
//	private final String TAG = "ProductDetailActivity";
	private final String SERVICE_NUMBER = "01088499999";
	
	private int pId;
	private Product product;
	private Gallery gallery;
	private TextView textProductNameValue;
	private TextView textProductIdValue;
	private TextView textOriginalPriceValue;
	private RatingBar textProdGradeValue;
	private TextView textPriceValue;
	private EditText prodNumValue;
	private RelativeLayout prod_property;
	private TextView textProdIsStock;
	private TextView textProductCommentNum;
	private TextView textProductInfoIsNull;
	private RelativeLayout relTop;
	private ProductEngine productEngine;
	private GalleryAdapter adapter;
	private List<String> pics;
	private SoftMap<String, Bitmap> bitmaps = new SoftMap<String, Bitmap>();
	private Spinner textSizeValue;
	private Spinner textColorValue;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.product_detail_activity);
		
		pId = getIntent().getIntExtra("pId", 0);
		
		init();
		getData();
	}

	/**
	 * 初始化
	 */
	private void init() {
		relTop = (RelativeLayout) findViewById(R.id.relTop);
		TextView tv_back = (TextView) findViewById(R.id.titleBack);//返回按钮
		gallery = (Gallery) findViewById(R.id.productGallery);//商品图片
		
		textProductNameValue = (TextView) findViewById(R.id.textProductNameValue);//商品名
		textProductIdValue = (TextView) findViewById(R.id.textProductIdValue);//商品id
		textOriginalPriceValue = (TextView) findViewById(R.id.textOriginalPriceValue);//商品原始价格
		textProdGradeValue = (RatingBar) findViewById(R.id.textProdGradeValue);//商品评分
		textPriceValue = (TextView) findViewById(R.id.textPriceValue);//会员价
		prodNumValue = (EditText) findViewById(R.id.prodNumValue);//购买数量
		
		prod_property = (RelativeLayout) findViewById(R.id.prod_property);//商品属性
		textColorValue = (Spinner) findViewById(R.id.textColorValue);
		textSizeValue = (Spinner) findViewById(R.id.textSizeValue);
		
		TextView textPutIntoShopcar = (TextView) findViewById(R.id.textPutIntoShopcar); //加入购物车
		TextView textProdToCollect = (TextView) findViewById(R.id.textProdToCollect); //加入收藏
		
		RelativeLayout relDescription = (RelativeLayout) findViewById(R.id.relDescription); //商品描述item，可点击
		RelativeLayout relProdStock = (RelativeLayout) findViewById(R.id.relProdStock); //商品库存item，可点击
		textProdIsStock = (TextView) findViewById(R.id.textProdIsStock);//库存数量
		RelativeLayout relProductComment = (RelativeLayout) findViewById(R.id.relProductComment); //商品评论item，可点击
		textProductCommentNum = (TextView) findViewById(R.id.textProductCommentNum);//评论总数
		
		TextView orderTelTv = (TextView) findViewById(R.id.orderTelTv); //订购热线
		textProductInfoIsNull = (TextView) findViewById(R.id.textProductInfoIsNull);//商品为空时
		
		//---------------------------------添加监听器------------------------------------
		tv_back.setOnClickListener(this);
		textPutIntoShopcar.setOnClickListener(this);
		textProdToCollect.setOnClickListener(this);
		relDescription.setOnClickListener(this);
		relProdStock.setOnClickListener(this);
		relProductComment.setOnClickListener(this);
		orderTelTv.setOnClickListener(this);
		
		adapter = new GalleryAdapter();
		gallery.setAdapter(adapter);
		gallery.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent bigpic_intent = new Intent(ProductDetailActivity.this, ProductBigPicActivity.class);
				bigpic_intent.putExtra("product", product);
				bigpic_intent.putExtra("position", position);
				startActivityForResult(bigpic_intent, 110);
			}
		});
		
	}
	
	/**
	 * 后台获取数据
	 */
	private void getData() {
		new MyHttpTask() {
			@Override
			protected void onPreExecute() {
				PromptManager.showProgressDialog(ProductDetailActivity.this);
			};
			@Override
			protected Object doInBackground(Void... params) {
				productEngine = DaoAndEngineFactory.getImpl(ProductEngine.class);
				Product product = productEngine.getProductDetailInfo(pId);
				return product;
			}
			@Override
			protected void onPostExecute(Object result) {
				PromptManager.closeProgressDialog();
				if(result == null) {
					textProductInfoIsNull.setVisibility(View.VISIBLE);
					relTop.setVisibility(View.GONE);
				} else {
					product = (Product) result;
					
					showView();
				}
			};
		}.executeHttp();
	}
	
	/**
	 * 显示界面组件
	 */
	protected void showView() {
		textProductNameValue.setText(product.getName());
		textProductIdValue.setText(product.getId() + "");
		textOriginalPriceValue.setText("￥ " + product.getMarketprice());
		//删除线
		textOriginalPriceValue.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG );
		//抗锯齿
		textOriginalPriceValue.getPaint().setAntiAlias(true);
		textPriceValue.setText("￥ " + product.getPrice());
		int progress = new Random().nextInt(5) + 6;
		textProdGradeValue.setProgress(progress);
		System.out.println(progress + "::" + textProdGradeValue.getMax());
		
		pics = product.getPics();
		adapter.notifyDataSetChanged();
		
		List<ProductProperty> propertys = product.getProduct_property();
		if(propertys != null && propertys.size() != 0) {
			prod_property.setVisibility(View.VISIBLE);
			List<String> colorlist = new ArrayList<String>();
			List<String> sizelist = new ArrayList<String>();
			for (ProductProperty property : propertys) {
				if("颜色".equals(property.getPkey())) {
					colorlist.add(property.getValue());
				} else if("大小".equals(property.getPkey())) {
					sizelist.add(property.getValue());
				}
			}
			textColorValue.setAdapter(new PropertySpinnerAdapter(colorlist.toArray()));
			textSizeValue.setAdapter(new PropertySpinnerAdapter(sizelist.toArray()));
		} else {
			prod_property.setVisibility(View.GONE);
		}
		
		String area = product.getInventoryarea();
		textProdIsStock.setText((area == null ? "" : area) + " ( " + (product.getAvailable() > 0 ? "有货" : "无货") + " )");
		textProductCommentNum.setText(product.getCommentcount() + "");
	}

	class GalleryAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			if(pics == null || pics.size() == 0)
				return 0;
			return pics.size();
//			return Integer.MAX_VALUE;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if(convertView == null) {
				convertView = new ImageView(ProductDetailActivity.this);
			}
			final ImageView iv = (ImageView) convertView;
			iv.setScaleType(ImageView.ScaleType.FIT_XY);
			
//			Log.i(TAG, pics.get(position));
//			ImageUtil.loadImageFromUrl(iv, pics.get(position));
//			getImage(pics.get(position), position);
			
			final String imgurl = pics.get(position % pics.size());
			if(bitmaps.containsKey(imgurl)){
				iv.setImageBitmap(bitmaps.get(imgurl));
			} else {
				new MyHttpTask() {
					@Override
					protected Object doInBackground(Void... params) {
						try {
							URL rl = new URL(imgurl);
							InputStream is = rl.openStream();
							Bitmap bmp = BitmapFactory.decodeStream(is);
							return bmp;
						} catch (Exception e) {
							e.printStackTrace();
						}
						return null;
					}
					@Override
					protected void onPostExecute(Object result) {
						if(result != null) {
							Bitmap bmp = (Bitmap) result;
							iv.setImageBitmap(bmp);
							bitmaps.put(imgurl, bmp);
						}
					};
				}.executeHttp();
			}
			
			return iv;
		}
		@Override
		public Object getItem(int position) {
			return position;
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
	}
	
	class PropertySpinnerAdapter extends BaseAdapter {
		private Object[] attrs;
		PropertySpinnerAdapter(Object[] attrs) {
			this.attrs = attrs;
			System.out.println(attrs);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView == null) {
				convertView = View.inflate(ProductDetailActivity.this, R.layout.spinner_item, null);
			}
			TextView tv_spinner = (TextView) convertView.findViewById(R.id.tv_spinner);
			tv_spinner.setText(attrs[position].toString());
			return convertView;
		}
		
		@Override
		public int getCount() {
			return attrs.length;
		}
		@Override
		public Object getItem(int position) {
			return attrs[position].toString();
		}
		@Override
		public long getItemId(int position) {
			return 0;
		}
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.titleBack:
			finish();
			break;
		case R.id.textPutIntoShopcar:
			String num = prodNumValue.getText().toString().trim();
//			String selectedColor = textColorValue.getSelectedItem().toString();
//			String selectedSize = textSizeValue.getSelectedItem().toString();
//			System.out.println(selectedColor + ":::::" + selectedSize);
			
			GloableParams.isProductCatergery = true;
			Intent shopcar_intent = new Intent(this, CartActivity.class);
			shopcar_intent.putExtra("product_id", pId);
			shopcar_intent.putExtra("num", Integer.valueOf(num));
			startActivity(shopcar_intent);
			break;
		case R.id.textProdToCollect:
			if(GloableParams.isLogin)
				addCollectInServer(pId,GloableParams.userid);
			else {
				PromptManager.showToast(this, "请先登录!");
				Intent login_intent = new Intent(this, LoginActivity.class);
				startActivity(login_intent);
			}
			break;
		case R.id.relDescription:
			Intent desc_intent = new Intent(this, ProductDescActivity.class);
			desc_intent.putExtra("pId", pId);
			desc_intent.putExtra("pName", product.getName());
			startActivity(desc_intent);
			
			break;
		case R.id.relProdStock:
			break;
		case R.id.relProductComment:
			Intent comment_intent = new Intent(this, ProductCommentActivity.class);
			comment_intent.putExtra("pId", pId);
			startActivity(comment_intent);
			break;
		case R.id.orderTelTv:
			Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:" + SERVICE_NUMBER));  
            startActivity(intent);
			break;
		}
	}
	
	/**
	 * 在服务器端添加收藏
	 * @param pId 商品id
	 */
	private void addCollectInServer(final int pId, final int userid) {
		new MyHttpTask() {
			@Override
			protected Object doInBackground(Void... params) {
				boolean res = productEngine.addFavorite(pId,userid);
				return res;
			}
			@Override
			protected void onPostExecute(Object result) {
				boolean res = (Boolean) result;
				String text = res ? "添加商品到收藏夹成功！" : "商品已经存在于收藏夹中！";
				PromptManager.showToast(ProductDetailActivity.this, text);
			}
		}.executeHttp();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == 110 && resultCode == RESULT_OK) {
			if(data != null) {
				int position = data.getIntExtra("position", 0);
				gallery.setSelection(position > (pics.size() - 1) ? pics.size() : position);
			}
		}
	}
}
